package com.fire.threadpool.nameThreadFactory;

import java.util.concurrent.ThreadFactory;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * NameThreadFactory
 *
 * @author zwd
 * @date 2022/3/23
 * @desc
 */
public class NameThreadFactory implements ThreadFactory {
    private static final AtomicInteger poolNumber = new AtomicInteger(1);
    private final ThreadGroup group;
    private final AtomicInteger threadNumber = new AtomicInteger(1);
    private final String namePrefix;
    private final boolean daemon;

    public NameThreadFactory(){
        this("pool-" + poolNumber.getAndIncrement(),false);
    }

    public NameThreadFactory(String namePrefix) {
        this(namePrefix, false);
    }

    public NameThreadFactory(String namePrefix, boolean daemon){
        this.namePrefix = namePrefix + "-thread-";
        this.daemon = daemon;
        SecurityManager s = System.getSecurityManager();
        group = (s == null) ? Thread.currentThread().getThreadGroup() : s.getThreadGroup();
    }


    @Override
    public Thread newThread(Runnable r) {
        String name = namePrefix + threadNumber.getAndIncrement();
        Thread ret = new Thread(group, r, name, 0);
        ret.setDaemon(daemon);
        return ret;
    }

    public ThreadGroup getThreadGroup() {
        return group;
    }
}
